<template>
  <div class="plan-add-termina-view">

    <div class="btn-view">

      <!--            <el-button type="primary" size="small" plain>从Excel导入</el-button>-->

      <el-button plain size="small" type="primary" @click="addApp">添加终端</el-button>

      <el-button plain size="small" type="primary" @click="addAllApp">批量添加终端</el-button>

      <el-button plain size="small" type="primary" @click="setingClick">设置开发信息</el-button>

      <el-button plain size="small" type="danger" @click="allDelete">批量移除</el-button>

    </div>

    <el-table
        :cell-style="cellStyle"
        :data="tableData"
        border
        header-cell-class-name="table-header"
        @row-click="rowClick"
        @selection-change="handleSelectionChange"
        @cell-dblclick="cellDblclick"
    >
      <el-table-column type="selection" width="40"/>
      <el-table-column align="center" header-align="center" label="终端名称" min-width="100" prop="terminalName"
                       show-overflow-tooltip>
        <template #default="scope">
          <span>{{ scope.row.terminalName }}</span>
          <template v-if="scope.row.validStatus">
            <el-popover
                :width="200"
                placement="bottom"
                trigger="click"
            >
              <template #reference>
                <el-icon style="margin-left: 5px">
                  <info-filled/>
                </el-icon>
              </template>

              <div>
                <span v-if="datas.errMap" style="color:red">{{ datas.errMap[scope.row.validStatus] }}</span>
              </div>
            </el-popover>
          </template>

        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="所在地区" prop="area" show-overflow-tooltip/>
      <el-table-column align="center" header-align="center" label="营销体量" min-width="120">
        <template #default="scope">
          <div v-if="scope.row.isEdit && !scope.row.validStatus" class="cell-view">
            <el-select v-model="scope.row.salesVolume" placeholder="请选择营销体量">
              <el-option
                  v-for="item in sellOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </div>
          <div v-else>
            {{ getLabel('sales_volume', scope.row.salesVolume) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="开发期限截止日期" min-width="120">
        <template #default="scope">
          <div v-if="scope.row.isEdit && !scope.row.validStatus" class="cell-view">
            <!--                        <el-date-picker v-model="scope.row.expireTime" type="date" placeholder="请选择截止日期" :disabled-date="disabledDate" @change="dateChange(scope.row)">-->
            <!--                        </el-date-picker>-->
            <date-picker v-model:date="scope.row.expireTime" :disabled-date="disabledDate" placeholder="请选择截止日期"
                         @change="dateChange(scope.row)"/>
          </div>
          <div v-else>
            {{ dateFormat('yyyy-mm-dd', scope.row.expireTime) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="开发保证金(元)" width="130px">
        <template #default="scope">
          <div v-if="scope.row.isEdit && !scope.row.validStatus" class="cell-view">
            <el-input :ref="(el)=>{setExploitInput(el,scope)}" v-model.number="scope.row.devEarnestMoney"
                      clearable oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入开发保证金"
                      @blur="exploitBlur(scope.row)"/>
          </div>
          <div v-else>
            {{ scope.row.exploitPrice }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="最低销量" min-width="170">
        <template #default="scope">

          <div v-if="scope.row.isEdit && !scope.row.validStatus" style="width: 100%">
            <el-input :ref="(el)=>{setExploitInput(el,scope)}" v-model.number="scope.row.minSale" clearable
                      oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入最低销量" style="width: 100%"
                      @blur="salesBlur(scope.row)">
              <template #append>
                <span style="margin-right: 10px">{{ getLabel('sell_unit', datas.planInfo.sellUnit) }}/</span>
                <el-select v-model="scope.row.minSaleUnit" clearable placeholder="" style="width: 60px"
                           @change="unitChange(scope.row)">
                  <el-option
                      v-for="item in unitOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </template>
            </el-input>

          </div>
          <div v-else>
            {{ scope.row.minSale }}{{ getLabel('sell_unit', datas.planInfo.sellUnit) }}/{{ getLabel('sell_num_unit', scope.row.minSaleUnit) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="销量保证金(元)" width="130px">
        <template #default="scope">
          <div v-if="scope.row.isEdit && !scope.row.validStatus" class="cell-view">
            <el-input :ref="(el)=>{setExploitInput(el,scope)}" v-model.number="scope.row.sellEarnestMoney"
                      clearable oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入销量保证金"
                      @blur="salesPriceBlur(scope.row)"/>
          </div>
          <div v-else>
            {{ scope.row.salesStr }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="其他说明">
        <template #default="scope">
          <div v-if="scope.row.isEdit && !scope.row.validStatus" class="cell-view">
            <el-input :ref="(el)=>{setExploitInput(el,scope)}" v-model="scope.row.remark" clearable
                      placeholder="请输入其他说明" @blur="otherBlur(scope.row)"/>
          </div>
          <div v-else>
            {{ scope.row.remark }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="操作" width="60px">
        <template #default="scope">
          <el-button type="text" @click="onDelete(scope)">移除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <add-terminal-dialog :id="planId" :propsProduct="datas.planInfo" ref="appDialog" :list="list" :unit="datas.planInfo.sellUnit"
                         isVolime @confirm="(data) => {appConfirm([data])}"/>
    <!--        <add-app-dialog ref="appDialog" :id="planId" :list="list" @confirm="(data) => {appConfirm([data])}"></add-app-dialog>-->

    <all-app-dialog ref="allDialog" :area="area" :plan-id="planId" @confirm="appConfirm"/>

    <develop-setting-dialog ref="developDialog" :unit="datas.planInfo.sellUnit" @confirm="settingConfirm"/>

  </div>
</template>

<script>
import {InfoFilled} from '@element-plus/icons'
import {crmStore} from '@CRM/store'
import developSettingDialog from './developSettingDialog.vue'
import allAppDialog from './allAppDialog.vue'
import addAppDialog from './addAppDialog.vue'
import {computed, defineComponent, getCurrentInstance, reactive, ref, toRefs} from 'vue'

export default defineComponent({
  name: 'TerminaView',
  components: {addAppDialog, allAppDialog, developSettingDialog, InfoFilled},
  props: {
    list: {
      type: Array,
      default: []
    },
    area: {
      type: Array,
      default: []
    },
    planId: {
      type: Number,
      default: 0
    },
    deletes: {
      type: Array,
      default: []
    },
    datas: {
      type: Object,
      default: {}
    }
  },
  setup(props, {emit}) {
    const currentInstance = getCurrentInstance()
    var appDialog = ref(null)
    var allDialog = ref(null)
    var developDialog = ref(null)
    var refInput = reactive({})
    var deletes = ref([])
    var data = reactive({
      isEdit: false
    })

    var tableData = computed({
      get() {
        return props.list
      },
      set(val) {
        emit('update:list', val)
        return props.list
      }
    })

    const unitOptions = crmStore.getters['dictionary/getDictionary']['sell_num_unit']
    const sellOptions = crmStore.getters['dictionary/getDictionary']['sales_volume']

    var tableSelects = ref([])

    const refreshData = () => {
      deletes.value = []
    }

    const getInputRef = (label) => {
      let str = ''
      switch (label) {
        case '开发期限截止日期' :
          str = 'date'
          break
        case '开发保证金(元)' :
          str = 'exploit'
          break
        case '最低销量' :
          str = 'sales'
          break
        case '销量保证金(元)' :
          str = 'salePrice'
          break
        case '其他说明' :
          str = 'other'
          break
      }
      return str
    }

    const disabledDate = (time) => {
      return !(time.getTime() > Date.now())
    }

    const onInput = (value) => {
      value = value.replace(/^\.+|[^\d.]/g, '')
    }

    const rowClick = (row) => {

    }

    const cellStyle = (row) => {
      if (row.column.label === '操作') return
      return 'cursor: pointer;'
    }

    const handleSelectionChange = (val) => {
      console.log(val)
      tableSelects.value = val
    }

    const setExploitInput = (el, scope) => {
      const str = getInputRef(scope.column.label)
      refInput[str + scope.$index] = el
    }

    const cellDblclick = (row, column, cell, event) => {
      if (column.label == '终端名称' || column.label == '所在地区' ||
          (!row.isEdit && (column.label == '开发期限截止日期' ||
              column.label == '开发保证金(元)' ||
              column.label == '最低销量' ||
              column.label == '销量保证金(元)' ||
              column.label == '其他说明'))) {
        row.isEdit = !row.isEdit

        const index = props.list.findIndex(a => a.id == row.id)
        if (index != -1) {
          const str = getInputRef(column.label) + index
          setTimeout(() => {
            if (refInput[str]) {
              refInput[str].focus()
            }
          }, 500)
        }
      }
    }

    const exploitBlur = (row) => {
      if (row.devEarnestMoney) {
        row.exploitPrice = Number(row.devEarnestMoney)
        row.devEarnestMoney = Number(row.devEarnestMoney)
      } else {
        row.exploitPrice = ''
      }

      row.isExploit = false
    }

    const salesBlur = (row) => {
      if (row.minSale) {
        row.minSale = Number(row.minSale)
      } else {
        row.minSale = 0
      }

      row.isSales = false
    }

    const unitChange = (row) => {
      row.isSales = false
    }

    const salesPriceBlur = (row) => {
      if (row.sellEarnestMoney) {
        row.salesStr = row.sellEarnestMoney
        row.sellEarnestMoney = Number(row.sellEarnestMoney)
      } else {
        row.salesStr = ''
        row.sellEarnestMoney = 0
      }

      row.isSalesPrice = false
    }

    const otherBlur = (row) => {
      row.isOther = false
    }

    const dateChange = (row) => {
      row.isDateChange = false
      // row.expireTime = row.date//currentInstance.proxy.dateFormat('yyyy-mm-dd HH:MM:SS',row.date)
    }

    const onDelete = (scope) => {
      currentInstance.proxy
          .alertBox({
            message: '是否删除该终端？',
            title: '删除',
          })
          .then(() => {
            if (scope.row.id) {
              deletes.value.push(scope.row.id)
              console.log(deletes.value)
              emit('update:deletes', deletes.value)
            }
            const list = [...tableData.value]
            list.splice(scope.$index, 1)
            tableData.value = list

            emit('deleteData')
          })
          .catch((err) => {
            console.log(err)
          })
    }

    const allDelete = () => {
      if (!tableSelects.value.length) {
        currentInstance.proxy.customMessage({type: 'error', message: '请选择终端'})
        return
      }

      currentInstance.proxy
          .alertBox({
            message: '是否删除终端？',
            title: '删除',
          })
          .then(() => {
            tableSelects.value.forEach(item => {
              const index = props.list.findIndex(a => a.id == item.id)
              if (index != -1) {
                deletes.value.push(item.id)
                props.list.splice(index, 1)
              }
            })
            emit('update:deletes', deletes.value)
            emit('deleteData')
          })
          .catch((err) => {
            console.log(err)
          })
    }

    const addApp = () => {
      appDialog.value.openDialog()
    }

    const addAllApp = () => {
      allDialog.value.openDialog(props.datas.planInfo)
    }

    const setingClick = () => {
      if (!tableSelects.value.length) {
        currentInstance.proxy.customMessage({type: 'error', message: '请选择终端'})
        return
      }
      developDialog.value.openDialog()
    }

    const appConfirm = (list) => {
      console.log(list)
      //
      const a = []
      let str = ''
      for (let i = 0; i < list.length; i++) {
        if (!list[i].minSaleUnit) {
          list[i].minSaleUnit = '1'
        }
        if (!list[i].minSale) {
          list[i].minSale = 0
        }

        const index = tableData.value.findIndex(a => a.terminalId == list[i].terminalId)
        if (index == -1) {
          a.push(list[i])
        } else {
          if (str) {
            str = str + ','
          }
          str = str + list[i].terminalName
        }
      }
      if (str) {
        currentInstance.proxy.customMessage({type: 'error', message: str + '已添加'})
      }

      tableData.value = tableData.value.concat(a)

      emit('deleteData')
    }

    const settingConfirm = (data) => {
      console.log(data, tableSelects)
      tableSelects.value.forEach(item => {
        item.date = data.date
        item.expireTime = data.expireTime
        item.salesVolume = data.salesVolume
        item.dateStr = data.dateStr
        item.exploitPrice = data.exploitPrice
        item.devEarnestMoney = Number(data.devEarnestMoney)
        item.exploitStr = data.exploitStr
        item.minSale = Number(data.minSale)
        item.minSaleUnit = data.minSaleUnit
        item.sellEarnestMoney = Number(data.sellEarnestMoney)
        item.salesStr = data.salesStr
        item.remark = data.remark
        item.unitStr = data.unitStr
      })
    }

    const validate = () => {
      return new Promise((resolve, reject) => {
        if (!tableData.value.length) {
          currentInstance.proxy.customMessage({type: 'error', message: '请添加终端'})
          reject()
        } else {
          for (let i = 0; i < tableData.value.length; i++) {
            const ter = tableData.value[i]
            if (!ter.salesVolume) {
              currentInstance.proxy.customMessage({type: 'error', message: '请选择' + ter.terminalName + '终端的营销体量'})
              reject()
              break
            }
            if (!ter.expireTime) {
              currentInstance.proxy.customMessage({type: 'error', message: '请选择' + ter.terminalName + '终端的截止日期'})
              reject()
              break
            }
            if (!ter.devEarnestMoney) {
              currentInstance.proxy.customMessage({type: 'error', message: '请输入' + ter.terminalName + '终端的开发保证金'})
              reject()
              break
            }
          }

          resolve()
        }
      })
    }

    return {
      ...toRefs(data),
      allDialog,
      appDialog,
      tableData,
      developDialog,
      unitOptions,
      sellOptions,

      rowClick,
      cellStyle,
      handleSelectionChange,
      cellDblclick,
      exploitBlur,
      salesBlur,
      salesPriceBlur,
      otherBlur,
      dateChange,
      onDelete,
      allDelete,
      setExploitInput,
      addApp,
      appConfirm,
      addAllApp,
      settingConfirm,
      setingClick,
      unitChange,
      validate,
      onInput,
      disabledDate,
      refreshData
    }
  }
})
</script>

<style lang="scss">
@import "@/style/basics.scss";

.plan-add-termina-view {
  .btn-view {
    padding-bottom: $block-y;
  }

  .el-table {
    .el-table__body {
      .cell {
        .cell-view {
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .el-input {
          width: 160px;
        }

        .specail-input {
          display: flex;

          .el-input__inner {
            border-radius: 5px 0 0 5px;
          }

          .el-select {
            width: 100px;

            .el-input {
              width: 100px;

              .el-input__inner {
                width: 100px;
                border-radius: 0 5px 5px 0;
                border-left: 0;
              }
            }

          }
        }
      }
    }
  }

}
</style>
